#include "include/trackinfowidget.h"
#include "ui_trackinfowidget.h"
#include<taglib/fileref.h>
#include<taglib/tag.h>
TrackInfoWidget::TrackInfoWidget(const QString& file,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TrackInfoWidget)
{
    ui->setupUi(this);
    setFixedSize(362,307);
    fileName=file;
    fileRef=new TagLib::FileRef(fileName.toStdString().c_str());
    trackTag=fileRef->tag();
    initInfo();
    creatConnections();
}

TrackInfoWidget::~TrackInfoWidget()
{
    delete ui;
    delete fileRef;
}

void TrackInfoWidget::initInfo()
{
    if(trackTag)
    {
        artist=(trackTag->artist()).toCString(true);
        title=(trackTag->title()).toCString(true);
        album=(trackTag->album()).toCString(true);
        year=QString::number(trackTag->year());
        track=QString::number(trackTag->track());
        genre=(trackTag->genre()).toCString();
        comment=(trackTag->comment()).toCString();
        ui->fileNameInput->setText(fileName);
        ui->artistInput->setText(artist);
        ui->titleInput->setText(title);
        ui->albumInput->setText(album);
        ui->yearInput->setText(year);
        ui->genreInput->setText(genre);
        ui->commentInput->setText(comment);
    }
}

void TrackInfoWidget::creatConnections()
{
     connect(ui->closeBtn,SIGNAL(clicked()),this,SLOT(close()));
     connect(ui->saveBtn,SIGNAL(clicked()),this,SLOT(saveChanges()));
}

void TrackInfoWidget::saveChanges()
{
    artist=ui->artistInput->text();
    title=ui->titleInput->text();
    album=ui->albumInput->text();
    genre=ui->genreInput->text();
    year=ui->genreInput->text();
    track=ui->trackInput->text();
    comment=ui->commentInput->text();
    trackTag->setAlbum(TagLib::String(album.toStdString(),TagLib::String::UTF8));
    trackTag->setArtist(TagLib::String(artist.toStdString(),TagLib::String::UTF8));
    trackTag->setTitle(TagLib::String(title.toStdString(),TagLib::String::UTF8));
    trackTag->setGenre(TagLib::String(genre.toStdString(),TagLib::String::UTF8));
    trackTag->setComment(TagLib::String(comment.toStdString(),TagLib::String::UTF8));
    trackTag->setYear(year.toUInt());
    trackTag->setTrack(track.toUInt());
    if(fileRef->save())
        ui->updateLbl->setText(QObject::tr("Updated"));
    else
        ui->updateLbl->setText(QObject::tr("Failed To Update "));
}
